var util = require('../../utils/util.js');
let today = null;

// pages/reserve/index.js
const app = getApp();
var sliderWidth = 96;

Page({
  /**
   * 页面的初始数据
   */
  data: {
    reserveList: null,
    unReserveList: null,
    weekList: null,
    teacherList: null,
    teacherId: null,
    tabs: ["待约课程", "已约课程"],
    activeIndex: 0,
    sliderOffset: 0,
    actionSheetHidden: true,
    files: [],
    user: null,
    selectedTeacherAndDate_e: null,
    adList: null,
    index: 0,
    shopList: [],
    selectedShop: null
  },

  deleteReserve(e) {
    let that = this;
    console.log(e);
    let obj = e.currentTarget.dataset.obj;

    // 1 未预约，2已预约，3已开课
    if (obj.status > 2) {
      wx.showToast({
        title: '已开课不能取消预约',
        icon: 'none',
        duration: 2000
      });

      return;
    }

    wx.showModal({
      title: '提示',
      content: '确认取消预约吗？',
      success: function (res) {
        if (res.confirm) {
          wx.request({
            url: app.globalData.serverUrl + "/reserve/deleteReserve",
            header: {
              token: app.globalData.token
            },
            data: {
              reserveDetailId: obj.reserveDetailId
            },
            success(resp) {
              console.log(resp);
              if (resp.data.success) {
                that.queryMyReserve();

                wx.showToast({
                  title: '操作成功',
                  icon: 'none',
                  duration: 2000
                });
              }
            },
            fail(resp) {
              console.error(resp);
            }
          });

        } else if (res.cancel) {
          console.log('点击取消了');
        }
      }
    });
  },

  bindPickerChange(e) {
    this.setData({
      selectedShop: this.data.shopList[e.detail.value],
      index: e.detail.value,
    });

    this.data.weekList.forEach(element => {
      if (element.date == today)
        element.selected = true;
      else
        element.selected = false;
    });

    this.setData({
      weekList: this.data.weekList
    });

    this.refreshByTeacherIdAndDate(-1, today);
  },

  swiperClick(e) {
    console.log(e);

    wx.navigateTo({
      url: "./ad/index?adId=" + e.target.dataset.id
    })
  },

  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  showActionSheet() {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden,
    });
  },

  listenerActionSheet: function () {
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    });
  },

  refreshByTeacherIdAndDate(teacherId, _date) {
    console.log(teacherId, _date);
    let that = this;

    wx.showLoading({
      title: '加载中...',
    });
    wx.request({
      url: app.globalData.serverUrl + '/reserve/queryReserveByTeacherIdAndDate',
      header: {
        token: app.globalData.token
      },
      data: {
        startDate: _date,
        // teacherId: teacherId,
        teacherId: -1,
        shopId: that.data.selectedShop.id
      },
      success: function (resp) {
        wx.hideLoading();
        console.log(resp);

        if (resp.data.success) {
          // 解决苹果手机显示时间问题
          resp.data.data.forEach(element => {
            element.courseStartTime2 = element.courseStartTime.replace(/-/g, "/")
            element.courseEndTime2 = element.courseEndTime.replace(/-/g, "/")
          });
          
          that.setData({
            unReserveList: resp.data.data,
          });

        } else {
          that.setData({
            unReserveList: [{empty: true}]
          });
        }
      },
      fail: function (error) {
        wx.hideLoading();
        console.error(error);
      }
    });
  },

  reserve(e) {
    console.log(e);
    let that = this;

    wx.requestSubscribeMessage({
      tmplIds: ['1r48W1QffF-_1Nv2RaBOG9EcMoX_JMUON7GPviGqs_8'],
      success (res) { 
        
      }
    })

    if (app.globalData.sysUser.realName == null || app.globalData.sysUser.realName == "") {
      wx.showToast({
        title: '请先点击我的，填写个人信息后。再进行约课！',
        icon: 'none',
        duration: 2000
      });
      return;
    }

    wx.showModal({
      title: '提示',
      content: '确定预约吗？',
      success: function (sm) {
        if (sm.confirm) {
          // 用户点击了确定 可以调用删除方法了
          wx.request({
            url: app.globalData.serverUrl + '/reserve/updateReserve?reserveId=' + e.currentTarget.dataset.obj.id,
            method: "POST",
            header: {
              token: app.globalData.token
            },
            data: {
            },
            success: function (resp) {
              wx.hideLoading();
              console.log(resp);
              if (resp.data.success) {
                var _tmp = e.currentTarget.dataset.obj.courseStartTime.split(" ")[0];
                that.refreshByTeacherIdAndDate(e.currentTarget.dataset.obj.teacherId, _tmp);

                wx.showToast({
                  title: '预约成功',
                  icon: 'none',
                  duration: 2000
                });
                
              } else {
                wx.showToast({
                  title: resp.data.errorMsg,
                  icon: 'none',
                  duration: 2000
                });
              }
            },
            fail: function (error) {
              wx.hideLoading();
              console.error(error);
            }
          });

        } else if (sm.cancel) {
          console.log('用户点击取消')
        }
      }
    });
  },

  tabClick: function (e) {
    console.log(e);
    let that = this;

    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });

    if (e.currentTarget.id == 0) {
      
    }

    if (e.currentTarget.id == 1) {
      this.queryMyReserve();
    }
  },

  selectTeacher(e) {
    console.log(e);
    let that = this;

    that.setData({
      teacherId: e.currentTarget.dataset.item.id,
      files: e.currentTarget.dataset.item.photographList,
      user: e.currentTarget.dataset.item
    });

    let newTeacherList = [];
    this.data.teacherList.forEach(element => {
      console.log(element.id);
      console.log(e.currentTarget.dataset.item.id);
      if (element.id == e.currentTarget.dataset.item.id)
        element.selected = true;
      else
        element.selected = false;

      newTeacherList.push(element);
    });

    this.setData({
      teacherList: newTeacherList
    });

    let newWeekList = [];
    this.data.weekList.forEach(element => {
      element.selected = false;
      newWeekList.push(element);
    });

    this.setData({
      weekList: newWeekList
    });
    
  },

  // 点击日期列表刷新不同日期下的预约列表
  refreshReserveList(e) {
    console.log(e);
    let that = this;

    // that.setData({
    //   selectedTeacherAndDate_e: e
    // });

    this.data.weekList.forEach(element => {
      if (element.date == e.currentTarget.dataset.item.date)
        element.selected = true;
      else
        element.selected = false;
    });

    this.setData({
      weekList: this.data.weekList
    });

    wx.showLoading({
      title: '加载中...',
    });

    wx.request({
      url: app.globalData.serverUrl + '/reserve/queryReserveByTeacherIdAndDate',
      header: {
        token: app.globalData.token
      },
      data: {
        startDate: e.currentTarget.dataset.item.date,
        // teacherId: this.data.teacherId == null ? -1 : this.data.teacherId,
        teacherId: -1,
        shopId: that.data.selectedShop.id
      },
      success: function (resp) {
        wx.hideLoading();
        console.log(resp);
        if (resp.data.success) {
          // 解决苹果手机显示时间问题
          resp.data.data.forEach(element => {
            element.courseStartTime2 = element.courseStartTime.replace(/-/g, "/")
            element.courseEndTime2 = element.courseEndTime.replace(/-/g, "/")
          });

          that.setData({
            unReserveList: resp.data.data,
          });

        } else {
          that.setData({
            unReserveList: [{empty: true}]
          });
        }
      },
      fail: function (error) {
        wx.hideLoading();
        console.error(error);
      }
    });
  },

  queryMyReserve() {
    let that = this;

    // 查询已预约列表
    wx.request({
      url: app.globalData.serverUrl + '/reserve/queryMyReserve',
      header: {
        token: app.globalData.token
      },
      success: function (resp) {
        console.log(resp);
        if (resp.data.success) {
          // 解决苹果手机显示时间问题
          resp.data.data.forEach(element => {
            element.courseStartTime2 = element.courseStartTime.replace(/-/g, "/")
            element.courseEndTime2 = element.courseEndTime.replace(/-/g, "/")
          });
          
          that.setData({
            reserveList: resp.data.data,
          });
        }
      },
      fail: function (error) {
        console.error(error);
      }
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let that = this;

    today = util.formatDate(new Date());
    console.log(today);

    that.setData({
      adList: [{ id: '1', pic: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543492615510&di=c1c65e67e0f37c1cff61228b7dca7672&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimage%2Fc0%253Dshijue1%252C0%252C0%252C294%252C40%2Fsign%3Dbc7d115ce1f81a4c323fe48abf430a2c%2F500fd9f9d72a6059956342322234349b033bbaa3.jpg' },
      { id: '2', pic: 'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1543492732417&di=34c12482281700c777b8454dcd60fdd7&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2Fd4628535e5dde7117fdcf9d1acefce1b9d16618f.jpg' }]
    });

    // wx.setNavigationBarTitle({
    //   title: app.globalData.parentEnterpriseName == null ? "" : app.globalData.parentEnterpriseName
    // });

    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });

    // 日期列表8天
    wx.request({
      url: app.globalData.serverUrl + '/reserve/getWeekList',
      header: {
        token: app.globalData.token
      },
      success: function (resp) {
        console.log(resp);
        if (resp.data.success) {
          that.setData({
            weekList: resp.data.data,
          });

          that.data.weekList.forEach(element => {
            if (element.date == today)
              element.selected = true;
            else
              element.selected = false;
          });

          that.setData({
            weekList: that.data.weekList
          });
        }
      },
      fail: function (error) {
        console.error(error);
      }
    });

    // 店铺列表
    wx.request({
      url: app.globalData.serverUrl + '/reserve/shopList',
      header: {
        token: app.globalData.token
      },
      data: {
      },
      success: function (resp) {
        that.setData({
          shopList: resp.data,
          selectedShop: resp.data[0]
        });

        wx.request({
          url: app.globalData.serverUrl + '/reserve/queryReserveByTeacherIdAndDate',
          header: {
            token: app.globalData.token
          },
          data: {
            startDate: today,
            teacherId: -1,
            shopId: that.data.shopList[0].id
          },
          success: function (resp) {
            wx.hideLoading();
            console.log(resp);
            if (resp.data.success) {
              // 解决苹果手机显示时间问题
              resp.data.data.forEach(element => {
                element.courseStartTime2 = element.courseStartTime.replace(/-/g, "/")
                element.courseEndTime2 = element.courseEndTime.replace(/-/g, "/")
              });

              that.setData({
                unReserveList: resp.data.data,
              });
    
            } else {
              that.setData({
                unReserveList: [{ empty: true }]
              });
            }
          },
          fail: function (error) {
            wx.hideLoading();
            console.error(error);
          }
        });

      },
      fail: function (error) {
        console.error(error);
      }
    });

    


  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function (e) {
    return {
      title: "约课",
      imageUrl: "https://cw1.tw/CH/images/channel_master/af164017-3505-4e04-b1b3-bb45cd10cb94.jpg",
      path: "/pages/index/index?enterpriseId=" + app.globalData.enterpriseId,
      success: function (res) {
        var shareTickets = res.shareTickets;
        if (shareTickets.length == 0) {
          return false;
        }
        wx.getShareInfo({
          shareTicket: shareTickets[0],
          success: function (res) {
            var encryptedData = res.encryptedData;
            var iv = res.iv;
          }
        })
      },
      fail: function (res) {
        // 转发失败
        console.log(res);
      }
    }
  },
})